package com.zhoulu.service.borrow;

import com.zhoulu.constant.BorrowLimit;
import com.zhoulu.domain.book.BookBean;
import com.zhoulu.domain.borrowRecord.BorrowRecord;
import com.zhoulu.domain.user.UserBean;
import com.zhoulu.domain.util.LayuiResult;
import com.zhoulu.enums.RoleEnum;
import com.zhoulu.service.book.BookService;
import com.zhoulu.service.borrowRecord.BorrowRecordService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class BorrowService {

    @Autowired
    private BookService bookService;
    @Autowired
    private BorrowRecordService borrowRecordService;

    /**
     * 借书
     * @param bookId 图书id
     * @param qty 数量
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public LayuiResult borrowBook(Integer bookId, Integer qty) {
        // 1、判断此书是否还有库存
        BookBean bookSearch = new BookBean();
        bookSearch.setId(bookId);
        List<BookBean> bookList = bookService.findBookList(bookSearch);
        if(bookList == null || bookList.size() == 0){
            return LayuiResult.error("图书不存在，无法借书！");
        }
        BookBean book = bookList.get(0);
        if(book.getQty() - qty < 0){
            return LayuiResult.error("库存不足，无法借书！");
        }
        UserBean loginUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
        // 2、查询登录人的借阅记录，如果借书数量超过最大数量，不允许借书
        BorrowRecord recordSearch = new BorrowRecord();
        recordSearch.setUserId(loginUserBean.getId());
        List<BorrowRecord> borrowRecordList = borrowRecordService.findBorrowRecordList(recordSearch);
        Integer sum = 0;
        for (BorrowRecord record : borrowRecordList) {
            sum += record.getQty();
        }
        Integer maxBorrowNum = Integer.MAX_VALUE;
        if(RoleEnum.Student.getCode().equals(loginUserBean.getRoleCode())){
            maxBorrowNum = BorrowLimit.student;
        }else if(RoleEnum.Teacher.getCode().equals(loginUserBean.getRoleCode())){
            maxBorrowNum =BorrowLimit.teacher;
        }
        if(sum >= maxBorrowNum){
            return LayuiResult.error("已达到最大借书数量，无法借书！");
        }
        // 3、新增一条借书记录
        BorrowRecord recordInsert = new BorrowRecord();
        recordInsert.setBookId(bookId);
        recordInsert.setBorrowTime(new Date());
        recordInsert.setQty(qty);
        recordInsert.setUserId(loginUserBean.getId());
        borrowRecordService.insertBorrowRecord(recordInsert);
        // 4、库存 - qty
        book.setQty(book.getQty() - qty);
        bookService.updateBook(book);
        return LayuiResult.success("借书成功");
    }
}
